package com.everflourish.yeah100.act.markingsystem;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.FragmentStudentAdapter;
import com.everflourish.yeah100.adapter.ObjectAnswerAdapter;
import com.everflourish.yeah100.entity.marking.ObjectAnswer;
import com.everflourish.yeah100.entity.marking.Student;
import com.everflourish.yeah100.entity.marking.StudentAnswersLastModifiedTime;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.ui.dialog.SingleAnswerDialog;
import com.everflourish.yeah100.utils.AnswerUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.TopicUtil;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.StudentStatus;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者：Created by liqisi on 2016/10/21.
 * 时间：2016/10/21
 */
public class ObjectAnswerActivity extends BaseActivity implements View.OnClickListener {

    private Toolbar mToolBar;
    public static Student mStudent;
    private List<Topic> mTopics;
    private List<ObjectAnswer> mList;
    private GridView mStudentAnswerGv;
    //    private List<StandardAnswer> mStaList;
    public ArrayList<Map<String, Object>> mStaList;
    private ObjectAnswerAdapter mAdapter;
    private TextView mStudentNameTv;
    private TextView mHeaderScoreTv;
    private float mObjStudentScore;
    private float mObjTotalScore;
    //  数据是否有更新
    public boolean isUpdate = false;
    private TextView mSaveTv;
    public static LoadDialog mLoadDialog;
    private MarkingSystemRequest mRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_object_answer);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mStudent = (Student) getIntent().getSerializableExtra(
                IntentUtil.STUDENT_ANSWER);
        mTopics = (List<Topic>) getIntent().getSerializableExtra(IntentUtil.TOPIC);
        mStaList = (ArrayList<Map<String, Object>>) getIntent().getSerializableExtra(IntentUtil.STANDARD_ANSWER);
        setAnswerToList();
        mAdapter = new ObjectAnswerAdapter(mContext, mList, mStaList);
        mRequest = MarkingSystemRequest.getInstance();
    }

    private void initView() {
        mToolBar = (Toolbar) findViewById(R.id.toolbar_object_answer);
        mStudentNameTv = (TextView) findViewById(R.id.object_student_name);
        mHeaderScoreTv = (TextView) findViewById(R.id.header_score);
        mSaveTv = (TextView) findViewById(R.id.object_answer_save);
        mStudentAnswerGv = (GridView) findViewById(R.id.object_answer_gl);
        mStudentAnswerGv.setAdapter(mAdapter);
        mStudentAnswerGv.setOnItemClickListener(itemClickListener);
//        mSaveTv.setOnClickListener(this);
    }

    private void configView() {
        mToolBar.setTitle("客观题答案");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishMenuActivity();
            }
        });
        mStudentNameTv.setText(mStudent.getName());
        mObjTotalScore = AnswerUtil.getObjTotalScore(mTopics);
        setHeaderScore();
    }

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            showAlterDialog(position);
        }
    };

    /**
     * 把客观题字符串答案转为list
     */
    private void setAnswerToList() {
        String objectAnswer = mStudent.getAnswer().getObjectAnswers();
        mList = AnswerUtil.objectAnswerToList(objectAnswer, mTopics);
    }

    /**
     * 设置分数控件
     */
    private void setHeaderScore() {
        mObjStudentScore = AnswerUtil.getStudentGradeForList(mTopics, mStaList, mList);
        mHeaderScoreTv.setText("(" + mObjStudentScore + "/" + mObjTotalScore
                + ")分");
    }

    /**
     * 显示修改对话框
     *
     * @param position
     */
    private void showAlterDialog(final int position) {
        List<String> items = new ArrayList<String>();
        items.add("A");
        items.add("B");
        items.add("C");
        items.add("D");
        items.add("E");
        items.add("F");
        items.add("G");
        items.add("H");

        // 当点击了item后，弹出修改对话框
        boolean isSingle = true;
        int serialNumber = mList.get(position).getSerialNumber();
        final String answer = mList.get(position).getAnswer();
        int type = AnswerUtil.getCurrentTopicType(serialNumber, mTopics);
        String title = null;
        if (type == 1) {// 单选
            isSingle = true;
            title = "第" + serialNumber + "题(单选)： " + answer;
        } else if (type == 2) {// 多选
            isSingle = false;
            title = "第" + serialNumber + "题(多选)：" + answer;
        }
        final SingleAnswerDialog answerDialog = new SingleAnswerDialog(
                mContext, title, null, isSingle, false);
        answerDialog.setIsCancelShrinkFlag(true);
        answerDialog.setItems(items, answer,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 单选题
                        setPositionAnswer(position, answerDialog, answer);
                        if (position < mList.size() - 1) {
                            showAlterDialog(position + 1);
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                });

        String confirmButtonText = "下一题";
        if (position == mList.size() - 1) {
            confirmButtonText = "完成";
        }
        answerDialog.setOnConfirmButton(confirmButtonText,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPositionAnswer(position, answerDialog, answer);
                        dialog.dismiss();
                        if (position < mList.size() - 1) {
                            showAlterDialog(position + 1);
                        }
                    }
                });
        String cancelButtonText = "上一题";
        if (position == 0) {
            cancelButtonText = "完成";
        }
        answerDialog.setOnCancelButton(cancelButtonText,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPositionAnswer(position, answerDialog, answer);
                        dialog.dismiss();
                        if (position > 0) {
                            showAlterDialog(position - 1);
                        }
                    }

                });
        answerDialog.show();
    }

    /**
     * 设置item答案
     *
     * @param position
     * @param answerDialog
     * @param answer
     */
    private void setPositionAnswer(final int position,
                                   final SingleAnswerDialog answerDialog, String answer) {
        String currentAnswer = answerDialog.getAnswer();
        if (!currentAnswer.equals(answer)) {
            mList.get(position).setAnswer(currentAnswer);
            mAdapter.notifyDataSetChanged();
            isUpdate = true;
            setHeaderScore();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    /**
     * 设置关闭activity的数据
     */
    private void finishMenuActivity() {
        Intent resultIntent = getIntent();
        resultIntent.putExtra(IntentUtil.SINGLE_UPLOAD, isUpdate);
        MarkingMenuActivity.mFragmentReadPaper.isObjectOrSubjectInput = false;
        this.setResult(RESULT_OK, resultIntent);
        ObjectAnswerActivity.this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.object_answer_save:
                if (!isUpdate) {
                    MyToast.showLong(mContext, "答案没有修改");
                    return;
                }
                String content = AnswerUtil.listToObjectAnswer(mList, TopicUtil.getCurrentMaxNo(mTopics));
                mStudent.getAnswer().setObjectAnswers(content);
                mStudent.getAnswer().setObjectScores(mObjStudentScore);
                // 上传
                mStudent.getAnswer().setPaperType("N");
                mStudent.setStatus(StudentStatus.I.text);
                mStudent.setIsReadCard("1");
                MarkingMenuActivity.mFragmentReadPaper.isObjectOrSubjectInput = true;
                mLoadDialog = LoadDialog.show(mContext, null, "正在保存...", false);
                MarkingMenuActivity.mFragmentReadPaper.uploadSingleStudentAnswerRequest(mStudent, true, "1", false);
                break;
        }
    }

    /**
     * 上传单个学生答案请求
     *
     * @param student
     * @param isShowDialog
     * @param isObjectAnswer 1、客观题  2、主观题
     *                       是否显示对话框
     */
    public void uploadSingleStudentAnswerRequest(final Student student,
                                                 final boolean isShowDialog, final String isObjectAnswer) {
        new AsyncTask<Void, Void, Void>() {
            Student tempStudent = null;

            @Override
            protected void onPreExecute() {
                tempStudent = student;
                mLoadDialog = LoadDialog.show(mContext, null, "正在保存...", false, null);
                tempStudent.setUploadStatus(FragmentStudentAdapter.UPLOADING);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            protected synchronized Void doInBackground(Void... params) {
                while (MarkingMenuActivity.mFragmentReadPaper.uploadStudents.size() > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (mTopics == null || mTopics.size() == 0) {
                    return;
                }
                MarkingMenuActivity.mFragmentReadPaper.uploadStudents.add(tempStudent);
                if (TextUtils.isEmpty(tempStudent.getAnswer()
                        .getObjectAnswers())) {
                    tempStudent.getAnswer().setObjectAnswers(AnswerUtil
                            .topicsToAnswerContent(mTopics));
                }
                JsonObjectRequest request = mRequest
                        .uploadSingleStudentAnswersRequest(
                                MarkingMenuActivity.mExamination.getId(),
                                MarkingMenuActivity.mExamination
                                        .getLastModifiedTime(), MarkingMenuActivity.mFragmentReadPaper.mClassManages,
                                tempStudent, new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        uploadStudentAnswerExaminationListener(response, isObjectAnswer);
                                    }
                                }, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(
                                            VolleyError error) {
                                        uploadStudentAnswerExaminationErrorListener(error, isObjectAnswer);
                                    }
                                });
                mQueue.add(request);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * 上传学生答案监听
     *
     * @param response
     */
    private void uploadStudentAnswerExaminationListener(JSONObject response, String isObjcetAnswer) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                Student uploadStudent = MarkingMenuActivity.mFragmentReadPaper.uploadStudents.getFirst();
                uploadStudent.setUploadStatus(FragmentStudentAdapter.COMPLETE);
                MarkingMenuActivity.mFragmentReadPaper.uploadStudents.removeFirst();
                mAdapter.notifyDataSetChanged();
                if (isObjcetAnswer.equals("1")) {
                    MyToast.showShort(mContext, "保存学生答案成功");
                } else if (isObjcetAnswer.equals("2")) {
                    MyToast.showShort(mContext, "录入学生分数成功");
                } else if (isObjcetAnswer.equals("3")) {
                    MyToast.showShort(mContext, "上传学生答案成功");
                }
                // 统计总人数和参考数
                MarkingMenuActivity.isUpdateExamination = true;
                // 修改学生的最后修改时间
                List<StudentAnswersLastModifiedTime> studentAnswersLastModifiedTimes = null;
                if (response == null
                        || response.isNull("studentAnswersLastModifiedTimes")) {
                    studentAnswersLastModifiedTimes = new ArrayList<StudentAnswersLastModifiedTime>();
                } else {
                    JSONArray jsonArray = response
                            .getJSONArray("studentAnswersLastModifiedTimes");
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<StudentAnswersLastModifiedTime>>() {
                    }.getType();
                    studentAnswersLastModifiedTimes = gson.fromJson(
                            jsonArray.toString(), type);
                }
                for (StudentAnswersLastModifiedTime studentModifiedTime : studentAnswersLastModifiedTimes) {
                    Student student = MarkingMenuActivity.mFragmentReadPaper.mStudentMap.get(studentModifiedTime
                            .getStudentId());
                    if (student != null) {
                        student.setLastModifiedTime(studentModifiedTime
                                .getLastModifiedTime());
                    }
                }
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07071_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07072_000012E);
            } else if (resultCode.equals(ResultCode.result_200001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07073_200001E);
            } else if (resultCode.equals(ResultCode.result_200003E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07074_200003E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07075_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                MarkingMenuActivity.mFragmentReadPaper.isDataChange = true;
                MyToast.showShort(mContext, "当前数据已被更改，请刷新后操作");
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_070799_999999E);
            } else if (resultCode.equals(ResultCode.result_300017E.resultCode)) {
                MyToast.showShort(mContext, "请录入标准答案");
            } else {
                // TODO
                MyToast.showShort(mContext, "保存学生答案失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
        } finally {
            LoadDialog.dismiss(mLoadDialog);
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                Student uploadStudent = MarkingMenuActivity.mFragmentReadPaper.uploadStudents.getFirst();
                uploadStudent.setUploadStatus(FragmentStudentAdapter.UPLOAD_FAILURE);
                MarkingMenuActivity.mFragmentReadPaper.uploadStudents.removeFirst();
                MyToast.showShort(mContext, "保存学生答案失败");
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    private void uploadStudentAnswerExaminationErrorListener(VolleyError error, String isObjectAnswer) {
        Student uploadStudent = MarkingMenuActivity.mFragmentReadPaper.uploadStudents.getFirst();
        uploadStudent.setUploadStatus(FragmentStudentAdapter.UPLOAD_FAILURE);
        mAdapter.notifyDataSetChanged();
        MarkingMenuActivity.mFragmentReadPaper.uploadStudents.removeFirst();
        if (isObjectAnswer.equals("1")) {
            mRequest.disposeError(mContext,
                    mLoadDialog, error, "保存学生答案失败");
        } else if (isObjectAnswer.equals("2")) {
            mRequest.disposeError(mContext,
                    mLoadDialog, error, "录入学生分数失败");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_subject_upload, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.subject_upload_summit:
                if (!isUpdate) {
                    MyToast.showShort(mContext, "答案没有修改");
                    return false;
                }
                String content = AnswerUtil.listToObjectAnswer(mList, TopicUtil.getCurrentMaxNo(mTopics));
                mStudent.getAnswer().setObjectAnswers(content);
                mStudent.getAnswer().setObjectScores(mObjStudentScore);
                // 上传
                mStudent.getAnswer().setPaperType("N");
                mStudent.setStatus(StudentStatus.I.text);
                mStudent.setIsReadCard("1");
                MarkingMenuActivity.mFragmentReadPaper.isObjectOrSubjectInput = true;
                mLoadDialog = LoadDialog.show(mContext, null, "正在保存...", false);
                MarkingMenuActivity.mFragmentReadPaper.uploadSingleStudentAnswerRequest(mStudent, true, "1", false);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}